﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using myMvcBlog.Models;

namespace myMvcBlog.Controllers
{
    public class CategoryController : BaseController
    {
        //
        // GET: /Category/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult View(string nicename)
        {

            var posts = (from p in Post.All()
                         join pt in PostCategory.All() on p.ID equals pt.PostID
                         join c in Category.All() on pt.CategoryID equals c.ID
                         where c.UrlName == nicename
                         select p).OrderByDescending(p => p.PostedTime);

            int? page = null;

            if (!string.IsNullOrEmpty(Request.QueryString["page"]))
                page = int.Parse(Request.QueryString["page"]);

            ListView<Post> listView = new ListView<Post>();

            listView.Title = Category.SingleOrDefault(c => c.UrlName == nicename).Name;
            listView.List = posts.Skip((page ?? 0) * ItemsPerPage).Take(ItemsPerPage).ToList();

            PagerView pager = new PagerView();
            pager.ActionName = "View";
            pager.ControllerName = "Category";
            pager.CurrentPage = page ?? 1;
            pager.PageCount = (int)Math.Ceiling((double)posts.Count() / ItemsPerPage);

            listView.Pager = pager;

            return View(listView);
        }

    }
}
